from flask import Flask, session, g
from exts import db, mail
from blueprints.qa import bp as qa_bp
from blueprints.auth import bp as auth_bp
from flask_migrate import Migrate
from models import UserModel
import config

app = Flask(__name__)
# 绑定配置文件
app.config.from_object(config)
# db绑定app
db.init_app(app)
mail.init_app(app)
# 注册migrate
migrate = Migrate(app, db)
# 注册蓝图
app.register_blueprint(qa_bp)
app.register_blueprint(auth_bp)


# hooks钩子函数
# before_first_request
# after_request 响应拦截器
# before_request 请求拦截器
@app.before_request
def my_before_request():
    user_id = session.get('user_id')
    if user_id:
        user = UserModel.query.get(user_id)
        # g 是 flask的全局变量
        setattr(g, "user", user)
    else:
        setattr(g, "user", None)


# 上下文处理器，也类似全局变量
@app.context_processor
def my_context_processor():
    return {'user': g.user}


if __name__ == '__main__':
    app.run()
